package com.bt7274.task;

import com.bt7274.mapper.PostMapper;
import com.bt7274.mapper.ReactionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Set;
import java.time.LocalDateTime;
import java.util.Set;
@Component
public class PostReactionSyncTask {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ReactionMapper reactionMapper;

    @Autowired
    private PostMapper postMapper;

    private static final String LIKE_PREFIX = "post:like:";
    private static final String DISLIKE_PREFIX = "post:dislike:";
    private static final String DIRTY_POST_SET = "reaction:dirty_posts";

    // 每5分钟执行一次
    @Scheduled(cron = "0 0/1 * * * ?")
    // 定时任务，定期同步帖子点赞和点踩数量到数据库
    public void syncReactionsToDatabase() {
        // 获取发生过变化的帖子ID
        Set<String> dirtyPostIds = redisTemplate.opsForSet().members(DIRTY_POST_SET);

        if (dirtyPostIds != null && !dirtyPostIds.isEmpty()) {
            for (String postId : dirtyPostIds) {
                String likeKey = LIKE_PREFIX + postId;
                String dislikeKey = DISLIKE_PREFIX + postId;

                Long likeCount = redisTemplate.opsForSet().size(likeKey);
                Long dislikeCount = redisTemplate.opsForSet().size(dislikeKey);

                // 更新帖子表中的点赞和点踩数
                postMapper.updatePostLikeCounts(postId, likeCount != null ? likeCount.intValue() : 0);
                postMapper.updatePostDisLikeCounts(postId, dislikeCount != null ? dislikeCount.intValue() : 0);
            }

            // 同步完成后清空变化 Set
            redisTemplate.delete(DIRTY_POST_SET);
        }

        Set<String> dirtyViewPostIds = redisTemplate.opsForSet().members("post:dirty_views");

        if (dirtyViewPostIds != null) {
            for (String postId : dirtyViewPostIds) {
                String viewKey = "post:view:" + postId;

                // 获取 Redis 中当前点击量
                String viewCountStr = redisTemplate.opsForValue().get(viewKey);
                if (viewCountStr != null) {
                    int viewCount = Integer.parseInt(viewCountStr);
                    // 同步到数据库
                    postMapper.updatePostViewCount(postId, viewCount);
                }
            }

            // 清空脏数据集合（视情况可以保留一部分）
            redisTemplate.delete("post:dirty_views");
        }
    }
}
